package edu.zut.util;

import java.sql.*;

/**
 * 针对JDBC操作的工具类
 */
public class DBUtils {

    static final String DRIVERNAME="com.mysql.cj.jdbc.Driver";
    static final String URL = "jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    static final String USER="root";
    static final String PASSWORD="qwer1234";

    static {
        try {
            //驱动的加载
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    static Connection connection = null;
    static PreparedStatement statement = null;
    static ResultSet resultSet = null;
    /**
     * 获取数据库连接的方法
     * @return Connection
     */
    public static Connection getConn(){
        try {
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }


    /**
     * 查询
     * @param1 sql语句
     * @param2 sql中需要填充的参数
     */
    public static ResultSet query(String sql,Object... objs){
        connection = getConn();
        try {
            //sql预处理
            statement = connection.prepareStatement(sql);
            //判断objs是否为空或长度为0
            if (null != objs && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i+1,objs[i]);
                }
            }
            resultSet = statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }



    /**
     * 增删改的统一封装
     * @param sql sql语句
     * @param objs sql中需要填充的参数
     * @return int 表示受影响的行数
     */
    public static int update(String sql,Object... objs){
        connection = getConn();
        int result = 0;
        try {
            statement = connection.prepareStatement(sql);
            if (null != objs && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i + 1,objs[i]);
                }
            }
            result = statement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            free();
        }
        return result;
    }


    /**
     * 资源释放
     */
    public static void free(){
        if (null != resultSet){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != statement){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
